package com.sywb.chuangyebao.view;

import android.Manifest;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.czt.mp3recorder.MP3Player;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.sywb.chuangyebao.Constants;
import com.sywb.chuangyebao.R;
import com.sywb.chuangyebao.bean.QARichInfo;
import com.sywb.chuangyebao.bean.Question;
import com.sywb.chuangyebao.contract.AskContract;
import com.sywb.chuangyebao.utils.Utils;
import com.sywb.chuangyebao.widget.RichEditText;
import com.sywb.chuangyebao.widget.RichTextView;

import org.bining.footstone.BaseConstants;
import org.bining.footstone.log.Logger;
import org.bining.footstone.rxjava.rxbus.annotation.Subscribe;
import org.bining.footstone.rxjava.rxbus.annotation.Tag;
import org.bining.footstone.rxjava.rxbus.thread.ThreadMode;
import org.bining.footstone.utils.FileUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 提问、回答 编辑界面
 */
public class AskActivity extends ActionbarActivity<AskContract.Presenter> implements AskContract.AskView {

    @BindView(R.id.tv_cancel)
    TextView tvCancel;
    @BindView(R.id.tv_publish)
    TextView tvPublish;
    @BindView(R.id.actionbar_bottom_line)
    View actionbarBottomLine;
    @BindView(R.id.actionbar)
    RelativeLayout actionbar;
    @BindView(R.id.et_input)
    RichEditText etInput;
    @BindView(R.id.tv_record_time)
    TextView tvRecordTime;
    @BindView(R.id.iv_record_cancel)
    ImageView ivRecordCancel;
    @BindView(R.id.ll_record)
    LinearLayout llRecord;
    @BindView(R.id.common_recycler)
    RecyclerView commonRecycler;
    @BindView(R.id.iv_pic_add)
    ImageView ivPicAdd;
    @BindView(R.id.ll_pic)
    LinearLayout llPic;
    @BindView(R.id.iv_pic)
    ImageView ivPic;
    @BindView(R.id.iv_record)
    ImageView ivRecord;
    @BindView(R.id.iv_at)
    ImageView ivAt;
    @BindView(R.id.tv_ask)
    RichTextView tvAsk;
    @BindView(R.id.line_dash)
    View lineDash;

    public static final int COMING_TYPE_ASK = 0;//提问
    public static final int COMING_TYPE_ANSWER = 1;//回答

    private int type;//来自哪个界面
    private String text;//若为回答界面则有值，问题实体
    private String userName;//@人名称
    private int userId;//@人userId
    private String topicName;//话题名称
    private int topicId;//话题Id
    private boolean canEdit = true;
    private Question question;

    private int selectionEnd;
    private int currentPic;
    private String voicePath;
    private MP3Player mp3Player;

    private int beforeChar;

    @Override
    public int getLayoutId(Bundle bundle) {
        return R.layout.activity_ask;
    }

    @Override
    public void initView(Bundle bundle) {
        super.initView(bundle);
        if (bundle == null) {
            type = getIntent().getIntExtra("p0", 0);
            text = getIntent().getStringExtra("p1");
            userName = getIntent().getStringExtra("p2");
            userId = getIntent().getIntExtra("p3", 0);
            topicName = getIntent().getStringExtra("p4");
            topicId = getIntent().getIntExtra("p5", 0);
        } else {
            type = bundle.getInt("p0");
            text = bundle.getString("p1");
            userName = bundle.getString("p2");
            userId = bundle.getInt("p3");
            topicName = bundle.getString("p4");
            topicId = bundle.getInt("p5");
        }

        switch (type) {
            case COMING_TYPE_ASK:
                etInput.setHint(R.string.ask_hint);
                break;
            case COMING_TYPE_ANSWER:
                etInput.setHint("分享您的真实观点与经验");
                tvAsk.setVisibility(View.VISIBLE);
                lineDash.setVisibility(View.VISIBLE);

                if (!TextUtils.isEmpty(text)) {
                    question = JSON.parseObject(text, Question.class);
                    if (question == null) {
                        return;
                    }
                    tvAsk.setRichText(question.title, question.richInfoList);
                    tvAsk.setOnLinkClickListener(new RichTextView.OnLinkClickListener() {
                        @Override
                        public void onAtClick(RichTextView richTextView, Object userId) {
//                            int uid = (int) userId;
//                            if (uid == 0) {
//                                return;
//                            }
//
//                            advance(UserIndexActivity.class, uid);
                            Utils.goUserIndex(mActivity, (Integer) userId);
                        }

                        @Override
                        public void onTopicClick(RichTextView richTextView, Object topicId) {
                            advance(TopicActivity.class, topicId);
                        }

                        @Override
                        public void onEmojiClick(RichTextView richTextView, Object emoji) {

                        }

                        @Override
                        public void onUrlClick(RichTextView richTextView, Object url) {

                        }

                        @Override
                        public void onAllClick(RichTextView richTextView) {

                        }
                    });
                }


                break;
        }

        LinkedHashMap<Integer, String> richTexts = new LinkedHashMap<>();
        if (!TextUtils.isEmpty(userName)) {
            richTexts.put(userId, "@" + userName + BaseConstants.SPACE);
        }

        if (!TextUtils.isEmpty(topicName)) {
            richTexts.put(topicId, "#" + topicName + "#");
        }

        Logger.e("AskActivity.richTexts:" + JSON.toJSONString(richTexts));
        etInput.insertRich(richTexts);
        etInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                beforeChar = charSequence.length();
                // Logger.e("写了一个@.beforeTextChanged:" + charSequence + "beforeChar:" + beforeChar);
//                if (charSequence.length() > 0 && charSequence.charAt(charSequence.length() - 1) == '@' && canEdit) {
//                    canEdit = false;
//                    goAtSomeone();
//                }
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                // Logger.e("写了一个@.onTextChanged:" + charSequence + "光标位置：" + etInput.getSelectionStart() + "----" + etInput.getSelectionEnd());
//                if (etInput.getSelectionStart() > 0 && charSequence.length() >= etInput.getSelectionStart() && charSequence.charAt(etInput.getSelectionStart() - 1) == '@' && canEdit && beforeChar.length() <= charSequence.length()) {
//                    selectionEnd = etInput.getSelectionEnd();
//                    canEdit = false;
//                    goAtSomeone();
//                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
                // Logger.e("写了一个@.afterTextChanged:" + beforeChar);
                // Logger.e("写了一个@.afterTextChanged:" + editable + "光标位置：" + etInput.getSelectionStart() + "----" + etInput.getSelectionEnd());
                if (etInput.getSelectionStart() > 0 && editable.length() >= etInput.getSelectionStart() && editable.charAt(etInput.getSelectionStart() - 1) == '@' && canEdit && beforeChar < editable.length()) {
                    selectionEnd = etInput.getSelectionEnd();
                    canEdit = false;
                    goAtSomeone();
                }
            }
        });


    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putInt("p0", type);
        outState.putString("p1", text);
        outState.putString("p2", userName);
        outState.putInt("p3", userId);
        outState.putString("p4", topicName);
        outState.putInt("p5", topicId);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void initPresenter() {
        mPresenter.initPresenter(this);
    }

    @OnClick({R.id.iv_record, R.id.tv_cancel, R.id.iv_record_cancel, R.id.iv_at, R.id.tv_publish, R.id.iv_pic_add, R.id.iv_pic, R.id.tv_record_time
//            R.categoryId.iv_pic_cancel0, R.categoryId.iv_pic_cancel1, R.categoryId.iv_pic_cancel2,
    })
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_record:
                mPresenter.questPermissions(new String[]{Manifest.permission.RECORD_AUDIO});
                break;
            case R.id.tv_cancel:
                exit();
                break;
            case R.id.iv_record_cancel:
                llRecord.setVisibility(View.GONE);
                if (mp3Player != null && mp3Player.isPlaying()) {
                    mp3Player.stopPlay();
                    setRecordViewStart(false);
                }
                FileUtils.deleteFile(voicePath);
                voicePath = "";
                //删掉语音后  可以再录和选图片
                ivRecord.setVisibility(View.VISIBLE);
                ivPic.setVisibility(View.VISIBLE);
                break;
            case R.id.iv_at:
                goAtSomeone();
                break;
            case R.id.tv_publish:
                mPresenter.publish(type, question != null ? question.question_id : 0, etInput.getText().toString(), voicePath, etInput.getAllRichInfo(),
                        topicId, audioLength);
                break;
            case R.id.iv_pic_add:
            case R.id.iv_pic:
//                if (!TextUtils.isEmpty(voicePath)) {
//                    ToastUtils.show(mActivity, R.string.ask_type);
//                    return;
//                }
                // new ImgSelConfig.Builder().statusBarLightMode(true).backResId(R.drawable.ic_back_white).title("选择图片").maxNum(3 - currentPic).needCamera(true).needCrop(false).build(mActivity, 10001);

                // 进入相册,用不到的api可以不写
                PictureSelector.create(mActivity)
                        .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                        .theme(R.style.style_picture_white)//主题样式(不设置为默认样式) 也可参考demo values/styles下 例如：R.style.picture.white.style
                        .maxSelectNum(3 - currentPic)// 最大图片选择数量 int
                        .minSelectNum(0)// 最小选择数量 int
                        .imageSpanCount(4)// 每行显示个数 int
                        .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                        .previewImage(true)// 是否可预览图片 true or false
                        .previewVideo(false)// 是否可预览视频 true or false
                        .enablePreviewAudio(false) // 是否可播放音频 true or false
                        .isCamera(true)// 是否显示拍照按钮 true or false
                        .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                        .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                        .sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                        .setOutputCameraPath(FileUtils.getAppDefPath(FileUtils.PATH_IMAGE))// 自定义拍照保存路径,可不填
                        .enableCrop(false)// 是否裁剪 true or false
                        .compress(true)// 是否压缩 true or false
                        // .glideOverride()// int glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                        // .withAspectRatio()// int 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
                        // .hideBottomControls()// 是否显示uCrop工具栏，默认不显示 true or false
                        // .isGif()// 是否显示gif图片 true or false
                        .compressSavePath(FileUtils.getAppDefPath(FileUtils.PATH_IMAGE))//压缩图片保存地址
                        .freeStyleCropEnabled(true)// 裁剪框是否可拖拽 true or false
                        .circleDimmedLayer(false)// 是否圆形裁剪 true or false
                        .showCropFrame(true)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false   true or false
                        .showCropGrid(true)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false    true or false
                        .openClickSound(false)// 是否开启点击声音 true or false
                        // .selectionMedia()// 是否传入已选图片 List<LocalMedia> list
                        // .previewEggs()// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false
                        // .cropCompressQuality()// 裁剪压缩质量 默认90 int
                        .minimumCompressSize(100)// 小于100kb的图片不压缩
                        .synOrAsy(true)//同步true或异步false 压缩 默认同步
                        // .cropWH()// 裁剪宽高比，设置如果大于图片本身宽高则无效 int
                        // .rotateEnabled() // 裁剪是否可旋转图片 true or false
                        // .scaleEnabled()// 裁剪是否可放大缩小图片 true or false
                        // .videoQuality()// 视频录制质量 0 or 1 int
                        //  .videoMaxSecond(15)// 显示多少秒以内的视频or音频也可适用 int
                        // .videoMinSecond(10)// 显示多少秒以内的视频or音频也可适用 int
                        // .recordVideoSecond()//视频秒数录制 默认60s int
                        .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
                break;
            case R.id.tv_record_time:
                if (mp3Player == null) {
                    mp3Player = MP3Player.getInstance();
                    mp3Player.setOnMP3PlayerListener(new MP3Player.OnMP3PlayerListener() {
                        @Override
                        public void onCompletion(MediaPlayer mediaPlayer) {
                            Logger.e("MediaPlayer onCompletion");
                            setRecordViewStart(false);
                        }

                        @Override
                        public void onSeekComplete(MediaPlayer mediaPlayer) {
                            Logger.e("MediaPlayer onSeekComplete");
                        }

                        @Override
                        public void onError(MediaPlayer mediaPlayer) {
                            onCompletion(mediaPlayer);
                            showMessage("播放错误,请稍候再试");
                        }
                    });
                }
                if (mp3Player.isPlaying()) {
                    mp3Player.stopPlay();
                    setRecordViewStart(false);
                } else {
                    mp3Player.startPlay(voicePath, null);
                    setRecordViewStart(true);
                }
                break;
        }
    }


    private List<QARichInfo> richInfos;

    private void goAtSomeone() {
//        switch (type) {
//            case COMING_TYPE_ASK:
//                Logger.e("@前：" + JSON.toJSONString(etInput.getAllRichInfo()));
//                advance(ListCheckActivity.class, getString(R.string.ask_at), JSON.toJSONString(etInput.getAllRichInfo()));
//                break;
//            case COMING_TYPE_ANSWER:
//                advance(UserFriendsActivity.class, 3);
//                break;
//        }
        richInfos = new ArrayList<>();
        if (etInput.getAllRichInfo() != null && etInput.getAllRichInfo().size() > 0) {
            for (QARichInfo qaRichInfo : etInput.getAllRichInfo()) {
                if (qaRichInfo.uid == topicId) {
                    continue;
                }
                richInfos.add(qaRichInfo);
            }
        }

        Logger.e("@前：" + JSON.toJSONString(etInput.getAllRichInfo()) + "只有人：" + richInfos);
        advance(ListCheckActivity.class, getString(R.string.ask_at), JSON.toJSONString(richInfos));
    }

    public void setRecordViewStart(boolean isPlaying) {
        if (isPlaying) {
            Drawable drawable = getResources().getDrawable(R.drawable.stop_blue);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            if (tvRecordTime != null) {
                tvRecordTime.setCompoundDrawables(drawable, null, null, null);
            }
        } else {
            Drawable drawable = getResources().getDrawable(R.drawable.play_blue);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            if (tvRecordTime != null) {
                tvRecordTime.setCompoundDrawables(drawable, null, null, null);
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
//                case 10001:
//                    List<String> imageList = JSON.parseArray(data.getStringExtra("p0"), String.class);
//                    if (imageList != null && imageList.size() > 0) {
//                        llPic.setVisibility(View.VISIBLE);
//                        mPresenter.addPic(imageList);
//                    }
//                    break;
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    if (selectList != null && selectList.size() > 0) {
                        llPic.setVisibility(View.VISIBLE);

                        List<String> imageList = new ArrayList<>();
                        for (LocalMedia localMedia : selectList) {
                            imageList.add(localMedia.isCompressed() ? localMedia.getCompressPath() : localMedia.getPath());
                        }
                        mPresenter.addPic(imageList);
                    }
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    break;
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        mPresenter.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public boolean useRxBus() {
        return true;
    }

    @Subscribe(thread = ThreadMode.MAIN_THREAD, tags = {@Tag(Constants.POST_LIST_TUTOR)})
    public void rxAskAtBack(String data) {
        Logger.e("rxAskAtBack.data:" + data);
        if (TextUtils.isEmpty(data)) {
            canEdit = true;
            return;
        }

        //删掉之前的人
        if (richInfos != null && richInfos.size() > 0) {
            LinkedHashMap<Integer, String> oldUsers = new LinkedHashMap<>();
            for (QARichInfo qaRichInfo : richInfos) {
                oldUsers.put(qaRichInfo.uid, qaRichInfo.richName);
            }
            Logger.e("rxAskAtBack.delete:" + JSON.toJSONString(oldUsers));
            etInput.deleteRich(oldUsers);
        }

        LinkedHashMap<Integer, String> newUsers = JSON.parseObject(data, new TypeReference<LinkedHashMap<Integer, String>>() {
        });

        //处理@前原来的文字
        String originStr = etInput.getText().toString();
        if (!canEdit && selectionEnd > 0) {
            //去掉@字符
            if (!TextUtils.isEmpty(originStr) && originStr.charAt(selectionEnd - 1) == '@') {
                etInput.deleteNormalText(selectionEnd - 1, selectionEnd);
            }
            etInput.insertRich(selectionEnd - 1, newUsers);
        } else {
            Logger.e("rxAskAtBack.insert:" + JSON.toJSONString(newUsers));
            etInput.insertRich(newUsers);
        }

        canEdit = true;
    }


    private int audioLength;

    @Subscribe(thread = ThreadMode.MAIN_THREAD, tags = {@Tag(Constants.AUDIOCOMPLETE)})
    public void afterRecord(String data) {
        Logger.e("语音完成：" + data);
        HashMap<String, Object> hashMap = JSON.parseObject(data, new TypeReference<HashMap<String, Object>>() {
        });
        voicePath = hashMap.get("filePath").toString();
        audioLength = (int) hashMap.get("fileLength");
        tvRecordTime.setText(hashMap.get("audioLength").toString());
        if (mp3Player != null && mp3Player.isPlaying()) {
            mp3Player.stopPlay();
            setRecordViewStart(false);
        }
        llRecord.setVisibility(View.VISIBLE);

        //录好语音后  不能再录和选图片
        ivRecord.setVisibility(View.GONE);
        ivPic.setVisibility(View.GONE);

        try {
            String fileType = FileUtils.getFileType(voicePath);
            Logger.e("fileType:" + fileType);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public RecyclerView getRecyclerView() {
        return commonRecycler;
    }

    @Override
    public void setNoData(boolean isNoData) {
    }

    @Override
    public void picSizeChanged(int size) {
        currentPic = size;
        if (size == 3) {
            ivPicAdd.setVisibility(View.GONE);
            ivPic.setClickable(false);
            llPic.setVisibility(View.VISIBLE);

            //选了三张图后  不能再录语音和选图片
            ivRecord.setVisibility(View.GONE);
            ivPic.setVisibility(View.GONE);

        } else if (size == 0) {
            ivPicAdd.setVisibility(View.GONE);
            ivPic.setClickable(true);
            llPic.setVisibility(View.GONE);

            //取消选择图片了  可以选择录语音和选图片
            ivRecord.setVisibility(View.VISIBLE);
            ivPic.setVisibility(View.VISIBLE);
        } else {
            ivPicAdd.setVisibility(View.VISIBLE);
            ivPic.setClickable(true);
            llPic.setVisibility(View.VISIBLE);


            //选了一张或两张  不能再录
            ivRecord.setVisibility(View.GONE);
        }
    }

}
